<template>
  <div class="page-classifyList">
    <filter-view @update-list="() => getClassList()" />
    <a-table
      id="sortTable"
      :row-selection="{
        selectedRowKeys: statusState.selectedRowKeys,
        checkStrictly: false,
        onChange: onSelectChange
      }"
      :expandRowByClick="false"
      row-key="person_categ_id"
      :columns="columns"
      :data-source="state.classList"
      :loading="state.loading"
      :pagination="false"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'person_categ_person_count'">
          <span>
            {{ formatNumber(record.person_categ_person_count) }}
          </span>
        </template>
        <template v-else-if="column.key === 'person_categ_status'">
          <span>
            <a-switch
              v-model:checked="record.person_categ_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="updateMakerClass(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteMakerClass(record)"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该分类吗</span>
    </modal-view>
    <!-- 添加/编辑对话框 -->
    <modal-view
      :title="statusState.isAdd ? '添加分类' : '编辑分类'"
      v-model:visible="statusState.formVisible"
      okText="确定"
      cancelText="取消"
      :width="511"
      :afterClose="afterCloseEdit"
      @confirm="formConfirm"
      @cancel="formCancel"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules">
        <a-form-item label="分类名称" name="person_categ_name">
          <a-input
            v-model:value.trim="formState.person_categ_name"
            :maxlength="30"
            class="w-[359px]"
            placeholder="请输入分类名称"
          />
        </a-form-item>
        <a-form-item label="状态" name="person_categ_status">
          <a-radio-group v-model:value="formState.person_categ_status">
            <a-radio :value="1" class="mr-[80px]">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import Sortable from 'sortablejs'
import { formatNumber } from '@/utils/format'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import { classifyState, statusState } from './state'
import type { PersonClassList } from '@/types/site/filmMakerClassification'
import ModalView from '@/components/components/modal/ModalView.vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: { person_classify_list, edit_status, person_add_classify, person_update_classify, person_del_classify }
} = apis
const columns = ref(column)
const deleteVisible = ref(false)
const deleteId = ref()
const siteId = storage.get('siteId')
type Key = string
const state = reactive<{ loading: boolean; classList: PersonClassList[] }>({
  loading: false,
  classList: [] as PersonClassList[]
})
const formRef = ref()
interface IAddFormState {
  person_categ_name: string
  person_categ_status: number
  site_id?: string
  person_categ_id?: string
}
//添加分类form数据
const formState = reactive<IAddFormState>({
  person_categ_name: '',
  person_categ_status: 1
})
const formRules = reactive({
  person_categ_name: [{ required: true, message: '请输入分类名称' }]
})
//分类弹窗关闭事件
const afterCloseEdit = () => {
  formRef.value.resetFields()
}
//获取影人分类接口
const getClassList = () => {
  state.loading = true
  classifyState.site_id = siteId
  person_classify_list(classifyState)
    .then((res: any) => {
      state.classList = res?.person_categ ?? []
      console.log('分类列表: ', state.classList)
      state.loading = false
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//行删除
const deleteMakerClass = (item: PersonClassList) => {
  deleteVisible.value = true
  console.log(statusState.selectedRowKeys, '行删除id')
  deleteId.value = item.person_categ_id
}
//编辑
const updateMakerClass = (item: PersonClassList) => {
  statusState.formVisible = true
  statusState.isAdd = false
  formRef.value.resetFields() //清除字段校验结果
  const { person_categ_order, person_categ_person_count, ...params } = item
  Object.assign(formState, params)
}
const editStatus = (checked: number, row: PersonClassList) => {
  const data = {
    type: 10,
    status: checked,
    id: [row.person_categ_id]
  }
  console.log('data: ', data.id)
  edit_status(data).then(() => {
    message.success(checked === 1 ? '启用成功' : '禁用成功')
    getClassList()
  })
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  person_del_classify({ person_categ_id: [deleteId.value] }).then(() => {
    message.success('删除影人分类成功')
    deleteVisible.value = value
    getClassList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  添加编辑对话框事件
 */
const formConfirm = (value: any) => {
  console.log('value: ', value)
  formRef.value.validate().then(() => {
    statusState.formVisible = value
    if (statusState.isAdd) {
      formState.site_id = siteId
      console.log('formState: ', formState)
      person_add_classify
      person_add_classify(formState).then(() => {
        message.success('新增影人分类成功')
        statusState.formVisible = value
        getClassList()
      })
    } else {
      person_update_classify(formState).then(() => {
        message.success('编辑影人分类成功')
        statusState.formVisible = value
        getClassList()
      })
    }
  })
}
const formCancel = () => {
  statusState.formVisible = false
  formState.person_categ_name = ''
}
//调用排序接口
const sortFunc = (item: any) => {
  person_update_classify({
    ...item
  }).then(() => {
    message.success('排序成功')
    getClassList()
  })
}
//初始化表格拖动
const initSortable = () => {
  const el = document.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { person_categ_id, person_categ_name, person_categ_person_count, person_categ_status } =
        state.classList[startIndex]
      const { person_categ_order } = state.classList[endIndex]
      console.log('person_categ_order: ', person_categ_order)
      sortFunc({
        person_categ_id,
        person_categ_name,
        person_categ_order,
        person_categ_status,
        person_categ_person_count
      })
    }
  })
}
onMounted(() => {
  initSortable()
  getClassList()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-classifyList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(.ant-table-thead
      > tr
      > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
